package com.woniuxy.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dingpf
 * @version 1.0
 * @description
 * @create 2025/4/22 14:36
 */
public class TestJWT {

    public static void main(String[] args) throws JOSEException {
        //1：生成头部
        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
                .type(JOSEObjectType.JWT).build();

        System.out.println(header.toBase64URL());
        //2: 载荷（保存用户信息）
        Map userMap = new HashMap<>();
        userMap.put("id",1);
        userMap.put("name","admin");
        Payload payload = new Payload(userMap);

        System.out.println(payload.toBase64URL());

        //3：数字签名 加密 (头部+ 载荷+ 密钥)
        JWSObject jwsObject = new JWSObject(header,payload);

        String secretKey = "天王该地虎，宝塔镇河妖";
        MACSigner macSigner = new MACSigner(secretKey);
        jwsObject.sign(macSigner); //数字签名（加密）

        String jwt = jwsObject.serialize(); //序列化的方式得到jwt字符串
        System.out.println(jwt);


    }
}
